package com.pianzhu.blockchainemr.service.impl;

import com.pianzhu.blockchainemr.mapper.LoginMapper;
import com.pianzhu.blockchainemr.pojo.EmrUser;
import com.pianzhu.blockchainemr.service.LoginService;
import com.pianzhu.blockchainemr.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private LoginMapper loginMapper;

    @Override
    @Transactional
    public EmrUser login(EmrUser getLoginUserInfo) {
        String username = getLoginUserInfo.getUsername();
        String password = getLoginUserInfo.getPassword();
        EmrUser EUser = loginMapper.login(username, password);
        if (getLoginUserInfo!= null && getLoginUserInfo.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("id", EUser.getUserId());
            claims.put("username", username);
            claims.put("usertype", EUser.getUserType());
            //生成token
            String token = JWTUtils.createJWT(claims);
            log.info("login success, token: " + token);
            EUser.setToken(token);
            EUser.setPassword(null);
            return EUser;
        }
        return null;
    }

    @Override
    public void logout(String username) {
        LocalDateTime now = LocalDateTime.now();
        loginMapper.logout(username, now);
    }
}
